package com.lanmaoly.concurrent;

/**
 * 交替打印
 *
 * @author fangzhe.hou 2019-11-6 11:47:13
 */
public class ThreadPrintTest {
    private static int num = 0;
    private static volatile boolean flag = false;

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            for (; 100 > num; ) {
                if (!flag && (num == 0 || ++num % 2 == 0)) {
                    System.out.println(Thread.currentThread().getName() + ":" + num);
                    flag = true;
                }
            }
        });
        Thread thread2 = new Thread(() -> {
            for (; 100 > num; ) {
                if (flag && ++num % 2 == 1) {
                    System.out.println(Thread.currentThread().getName() + ":" + num);
                    flag = false;
                }
            }
        });

        thread1.start();
        thread2.start();
    }
}
